#!/usr/bin/perl -w
use strict;

use FindBin;
use lib ("$FindBin::Bin/..", "/net/cpp-group/Leo/bin");
use db_parameters;
use ensembl_parameters;
use chromosomes;

use DBI;


print STDERR <<"HEADLINE";
888888888888888888888888888888888888888888888888888888888888888888888

    custom

	Description:
		Fill ens_id, prot_exon, gene_loci from passing non-ensembl directories

888888888888888888888888888888888888888888888888888888888888888888888

HEADLINE





#
#	connect to panda
#
my $dbh = connect_to_panda();
use get_psql_time;
my $start_time = get_psql_time($dbh);



#_________________________________________________________________________________________

#	retrieve_prot_id_to_gene_id

#		Do this here rather than ens_id to avoid 
#		order dependencies and minimize coupling

#_________________________________________________________________________________________

sub retrieve_prot_id_to_disruption($\%)
{
	my ($sequence_dir, $prot_id_to_disruption) = @_;
	
	print STDERR "\tReading disruptions map\n";
	my $disruptions_file = "$sequence_dir/disruptions.map";
	die "Error:\n\t$disruptions_file does not exist\n" unless (-f "$disruptions_file");
	open FILE, $disruptions_file or die;
	my $cnt_line = 0;
	while (<FILE>)
	{
		++$cnt_line;
		chomp;
		my ($prot_id, $count) = split /\t/;
		$prot_id_to_disruption->{$prot_id} = $count;
	}
}



#
#	get ensembl taxa
#
my %ensembl_taxa;
for my $ens_data(get_ensembl_taxon_data())
{
	++$ensembl_taxa{$ens_data->[TAXON]};
}

#
#	get custom
#
my %taxon_data = get_taxon_data;
for my $taxon(keys %taxon_data)
{
	next if exists $ensembl_taxa{$taxon};

	print STDERR "\tProcessing non-Ensembl species $taxon...\n";
	my $sequence_dir = $taxon_data{$taxon}[SEQ_DIR];


	my $id_prefix = $taxon_data{$taxon}[ID_PREFIX];
	$dbh->do("DELETE FROM taxon.prot_disruptions ".
			 "WHERE prot_id ~ '$id_prefix'");

	my %prot_id_to_disruption;
	retrieve_prot_id_to_disruption($sequence_dir, %prot_id_to_disruption);
	
	# copy to panda
	$dbh->do("COPY taxon.prot_disruptions(prot_id, disruptions_count) FROM STDIN");
	for my $prot_id(keys %prot_id_to_disruption)
	{
		$dbh->pg_putline("$prot_id\t$prot_id_to_disruption{$prot_id}\n");
	}
	$dbh->pg_putline("\\.\n");
	$dbh->pg_endcopy;
	$dbh->do("VACUUM ANALYSE taxon.prot_disruptions;");
	print STDERR "\t", scalar keys %prot_id_to_disruption, " disrupted transcripts placed ".
						"in taxon.prot_disruptions\n";
}

print STDERR "\tCompleted\n";

log_pipeline_stage($dbh, 'NULL', 20, 'table prot_disruptions', $start_time);
$dbh->disconnect();

